Skip to content

41.如何判断是 new 还是函数调用

this instanceof Person & arguments.callee

arguments.callee: 当前正在执行函数的引用

js
function Person(n,a){    
	this.name = n;
	this.age = a;
  // if(this instanceof arguments.callee){
	if(this instanceof Person){
		alert('new调用');
	}else{
		alert('函数调用');
	}
}
var p = new Person('jack',30); // --> new调用
// this 指向 p
Person(); // --> 函数调用

new.target != Person

new.target 是 ES6 引入的特性

js
function Person(n,a){    
	this.name = n;
	this.age = a;
	if (new.target === Person) {
		alert('new调用');
	}else{
		alert('函数调用');
	}
}
var p = new Person('jack',30); // --> new调用
Person(); // --> 函数调用

ES6 class

es6
class Person {
    constructor (name) {
        this.name = name;
    }
}
// Uncaught TypeError: Class constructor Person cannot be invoked without 'new'
console.log(Person())

在 MIT 许可下发布